package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RequestMapping("/api/user")
@RestController
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/address/list")
    public List<UserAddress> getCurrentUserAddress(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userService.getUserAddressListByUserId(userId);
    }

    @GetMapping("/passport/logout")
    public Result loginOut(@RequestHeader(value = "token",required = false) String headerToken,
                           @CookieValue(value = "token",required = false) String cookieToken){
        String token = headerToken;
        if (StringUtils.isEmpty(token)){
            token = cookieToken;
        }
        userService.loginOut(token);
        return Result.ok();
    }

    @PostMapping("/passport/login")
    public Result login(@RequestBody UserInfo info, HttpServletRequest request){
        UserInfo userInfo = userService.login(info);
        /**
         * 1、给Result里面返回这个数据
         *    map:
         *      token：   唯一令牌
         *      nickName：昵称
         *
         */
        if(userInfo == null){
            return Result.build(null, ResultCodeEnum.PASSWDERROR);
        }
        //登录成功
        Map<String, Object> success = userService.hanleLoginSuccess(userInfo,request);
        return Result.ok(success);
    }
}
